import axios from "axios";
import type {
  AxiosInstance,
  AxiosRequestConfig,
  AxiosResponse,
  InternalAxiosRequestConfig,
} from "axios";
import { useUserStore, useLoadStore } from "@/stores";
import { ElMessage } from "element-plus";
const userStore = useUserStore();
const loadStore = useLoadStore();
interface IHttpServiceConfig extends AxiosRequestConfig {
  baseURL?: string;
  timeout?: number;
}
class AxiosService {
  private instance: AxiosInstance;
  constructor(baseConfig: IHttpServiceConfig) {
    this.instance = axios.create({
      ...baseConfig,
      baseURL: baseConfig.baseURL || "http://localhost:8080/apis",
      timeout: baseConfig.timeout || 10000,
      headers: {
        "Content-Type": "application/json;charset=UTF-8",
      },
    });
    this.instance.interceptors.request.use(
      (config: InternalAxiosRequestConfig) => {
        config.headers.Authorization = "Bearer " + userStore.accessToken; //写在constructor里为静态，无法监听到userStore的变化
        loadStore.isLoading = true;
        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
    );
    this.instance.interceptors.response.use(
      (response: AxiosResponse) => {
        loadStore.isLoading = false;
        console.log(response.data, "response");
        if (response.data.status === 200) return response.data;
        else if (response.data.status === 401) {
          ElMessage.error("登录已过期，请重新登录");
        } else ElMessage.error(response.data.message);
      },
      (error) => {
        return Promise.reject(error);
      }
    );
  }
  /**
   * @param <T=any> 返回值类型 注：为用的时候.then里res的类型，用的时候可request.get<User>('/users')去指定
   */
  public get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return this.instance.get(url, config);
  }

  public post<T = any>(
    url: string,
    data?: any,
    config?: AxiosRequestConfig
  ): Promise<T> {
    return this.instance.post(url, data, config);
  }

  public put<T = any>(
    url: string,
    data?: any,
    config?: AxiosRequestConfig
  ): Promise<T> {
    return this.instance.put(url, data, config);
  }

  public delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return this.instance.delete(url, config);
  }
}
const request = new AxiosService({
  baseURL: "http://localhost:8080/apis",
  timeout: 5000,
});
export default request;
